package com.code.train.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.code.train.domain.DailyTrain;
import com.code.train.domain.DailyTrainExample;
import com.code.train.domain.Train;
import com.code.train.mapper.DailyTrainMapper;
import com.code.train.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
@Slf4j
public class DailyTrainGenService {


    @Autowired
    private DailyTrainMapper dailyTrainMapper;

    @Autowired
    private DailyTrainStationService dailyTrainStationService;

    @Autowired
    private DailyTrainCarriageService dailyTrainCarriageService;

    @Autowired
    private DailyTrainSeatService dailyTrainSeatService;

    @Autowired
    private DailyTrainTicketService dailyTrainTicketService;

    @Autowired
    private SkTokenService skTokenService;

    @Transactional
    public void genDailyTrain(Date date, Train train) {
        log.info("生成日期【{}】车次【{}】的信息开始", DateUtil.formatDate(date), train.getCode());
        //删除每日车次数据 车次之前低耦合
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.createCriteria().andDateEqualTo(date).andCodeEqualTo(train.getCode());
        dailyTrainMapper.deleteByExample(dailyTrainExample);

        //生成该车次的数据
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(train, DailyTrain.class);
        dailyTrain.setId(IdUtil.getSnowflake(1, 1).nextId());
        dailyTrain.setCreateTime(now);
        dailyTrain.setUpdateTime(now);
        dailyTrain.setDate(date);
        dailyTrainMapper.insert(dailyTrain);

        // 生成该车次的车站数据
        dailyTrainStationService.genDaily(date, train.getCode());

        //生成该车厢的数据
        dailyTrainCarriageService.genDaily(date, train.getCode());

        //生成该座位的数据
        dailyTrainSeatService.genDaily(date, train.getCode());

        //生成该余票的数据
        dailyTrainTicketService.genDaily(dailyTrain,date, train.getCode());

        //生成令牌
        skTokenService.genDaily(date, train.getCode());

        log.info("生成日期【{}】车次【{}】的信息结束", DateUtil.formatDate(date), train.getCode());

    }
}